<template>
  <div :id="id" class="bar-sty"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
  props: {
    id: String,
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    categoryData: {
      type: Array,
      default: () => {
        return []
      }
    },
    barWidth: {
      type: Number,
      default: () => {
        return 0
      }
    },
    interval: {
      type: Number,
      default: () => {
        return 0
      }
    },
    barRadius: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      // myChart: null,
      // chartDom: null
    }
  },
  computed: {
    // bothArraysHaveValues() {
    //   return this.data.length > 0 && this.categoryData.length > 0;
    // }
  },
  watch: {
    data(newData) {
      if (newData.length > 0 && this.categoryData.length > 0) {
        this.renderChart();
      }
    },
    categoryData(newCategoryData) {
      if (this.data.length > 0 && newCategoryData.length > 0) {
        this.renderChart();
      }
    }
  },
  mounted() {
    // 获取DOM元素，初始化Echarts图表对象，但不设置数据
    const chartDom = document.getElementById(this.id);
    const myChart = echarts.init(chartDom);
    // 将局部变量赋值给组件实例的属性，以便在其他方法中可以访问
    this.myChart = myChart;
    this.chartDom = chartDom;
    // 首次加载时尝试渲染图表（如果数据已经准备好）
    if (this.data.length > 0 && this.categoryData.length > 0) {
      this.renderChart();
    }
  },
  methods: {
    renderChart() {
      const option = {
        grid: {
          show: false,
          left: "0%",
          bottom: "15%",
          right: "0%"
        },
        tooltip: {
          show: true
        },
        xAxis: {
          type: 'category',
          data: this.categoryData,
          axisTick: {
            show: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(235, 239, 244, 1)"
            }
          },
          axisLabel: {
            show: true,
            color: "#1E1714",
            interval: this.interval
          }
        },
        yAxis: [{
          type: "value",
          show: false
        }],
        series: [
          {
            barMinHeight: 10,
            barWidth: this.barWidth,
            data: this.data,
            type: 'bar',
            barMinWidth: 10,
            // 取消鼠标移入高亮
            emphasis: {
              disabled: true,
              focus: 'none'
            },
            itemStyle: {
              borderRadius: this.barRadius, // 设置圆角的半径，顺序为左上、右上、右下、左下
            }
          }
        ]
      };
      this.myChart.setOption(option);
    }
  }
}
</script>

<style lang="less" scoped>
.bar-sty {
  width: 100%;
  height: 100%;
}
</style>